package cn.niit.letuseatdemo.controller.store;

import cn.niit.letuseatdemo.entity.domain.Classify;
import cn.niit.letuseatdemo.entity.domain.Goods;
import cn.niit.letuseatdemo.entity.groups.AddGroup;
import cn.niit.letuseatdemo.entity.groups.UpdateGroup;
import cn.niit.letuseatdemo.service.ClassifyService;
import cn.niit.letuseatdemo.service.GoodsService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 @Description: 处理【菜品管理】的控制器类
  * @Author: su_fuming
 * @CreateTime： 2022/10/11 10:37
 */
@Slf4j
@RequestMapping("/store/goods")
@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ClassifyService classifyService;

    /**
     * @Description: 菜品管理（列表）页面的初始化及查询
     * @Author: su_fuming
     * @CreateTime: 2022/10/11 16:15 Unclosed character class near index 10
     * [\ [|\]|\s]
     * ^
     * @return: java.lang.String
     **/
    @GetMapping
    public String index(Model model, Goods goods) {
        model.addAttribute("goods", goods);
        List<Goods> goodsList = goodsService.selectGoodsList(goods);
        PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);
        log.info("分页对象 = {}", pageInfo);

        log.info("查询出来的菜品列表：{}", goodsList);
        //第一个参数时该数据保存在域对象中的key,在页面中渲染数据时通过DepartmentList 来获取菜品集合
        model.addAttribute("goodsList", goodsList);
        model.addAttribute("pageInfo", pageInfo);
        return "store/goods/list";

    }

    /**
     * @Description: 接收用户请求，打开菜品添加、修改页面
     * 添加菜品、修改菜品共用一个页面
     * @Author: su_fuming
     * @CreateTime: 2022/10/13 9:20 Unclosed character class near index 10
     * [\ [|\]|\s]
     * ^
     * @return: java.lang.String
     **/
    @GetMapping("/{goodsId}")
    public String saveIndex(Model model, @PathVariable("goodsId") Long goodsId) {
        log.info("要修改的ID = " + goodsId);
        Goods goods = null;
        if (null != goodsId && goodsId > 0) { //值的修改
            goods = goodsService.selectGoodsByGoodsId(goodsId);
        } else {  //添加方法
            goods = new Goods();
        }

        List<Classify> classifyList = classifyService.selectClassifyList(new Classify());
        model.addAttribute("classifyList", classifyList);
        model.addAttribute("goods", goods);

        return "store/goods/add";
    }

    /**
     * @Description: 新增保存菜品
     * @Author: su_fuming
     * @CreateTime: 2022/10/13 10:17 Unclosed character class near index 10
     * [\ [|\]|\s]
     * ^
     * @return: java.lang.String
     **/
    @PostMapping
    public String addSave(@Validated(AddGroup.class) Goods goods, BindingResult result, Model model) {
        if (result.hasErrors()) {
            Map<String, String> errorsMap = new HashMap<>();
            for (FieldError error : result.getFieldErrors()) {
                log.error("参数校验错误:{},{}", error.getField(), error.getDefaultMessage());
                errorsMap.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("errors", errorsMap);
            model.addAttribute("goods", goods);
        }else {
            int rows = goodsService.insertGoods(goods);
            if (rows == 1) {
                /**如果插入成功，则重定向至菜品列表页面*/
                return "redirect:/store/goods";
            }
        }
        return "store/goods/add";
    }
    /**
     * @Description: 根据id修改菜品信息
     * @Author: su_fuming
     * @CreateTime: 2022/10/13 13:38 Unclosed character class near index 10
     * [\ [|\]|\s]
     * ^
     * @return: java.lang.String
     **/
    @PutMapping
    public String editSave(@Validated(UpdateGroup.class) Goods goods, BindingResult result, Model model) {
        if (result.hasErrors()) {
            Map<String, String> errorsMap = new HashMap<>();
            for (FieldError error : result.getFieldErrors()) {
                log.error("参数校验错误:{},{}", error.getField(), error.getDefaultMessage());
                errorsMap.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("errors", errorsMap);
            model.addAttribute("goods", goods);
        }else {
            int rows = goodsService.updateGoods(goods);
            if (rows == 1) {
                /**如果插入成功，则重定向至菜品列表页面*/
                return "redirect:/store/goods/";
            }
        }
        return "store/goods/add";
    }

    /**
     * @Description: 根据ID删除菜品信息
     * @Author: su_fuming
     * @CreateTime: 2022/10/13 15:05 Unclosed character class near index 10
     * [\ [|\]|\s]
     * ^
     * @return: java.lang.String
     **/
    @ResponseBody
    @DeleteMapping("/{goodsId}")
    public String delete(@PathVariable("goodsId") Long goodsId) {
        int rows = goodsService.deleteGoodsByGoodsId(goodsId);
        if (rows == 1) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * @Description: 菜品状态控制
     * @Author: su_fuming
     * @CreateTime: 2022/10/13 9:20 Unclosed character class near index 10
     * [\ [|\]|\s]
     * ^
     * @return: java.lang.String
     **/
    @GetMapping("/onDown/{goodsId}")
    public String onDown(@PathVariable("goodsId") Long goodsId) {
        log.info("要修改的ID = " + goodsId);
        Goods goods = null;
        if (null != goodsId && goodsId > 0) { //值的修改
            goods = goodsService.selectGoodsByGoodsId(goodsId);
        }
        goods.setGoodsStatus((goods.getGoodsStatus() + 1) % 2);
        goodsService.updateGoodsStatus(goods);
        return "redirect:/store/goods";
    }

}